/**
 * 
 */

var initializers = [];
var inited = false;

function addInitializer(fn) {
	if (!inited) {
		initializers.push(fn);
	} else {
		fn.call(this);
	}
}

function setContent(c) {
	for (var i = 0; i < initializers.length; i++) {
		initializers[i].call(this);
	}
	inited = true;
}

function getData() {
}

function addDescriptor(elDescriptor) {
	var count = 1;
	while($('#descriptorTemplate_' + count)[0]) {
		count++;
	}
	var str = $('#templatesContainer').html();
	str = str.replace(/__INDEX__/g, ''+count);
	$(str).appendTo('#descriptors');
	setDirtyFlag(true);
}

function deleteDescriptor(el) {
	$(el).parent().parent().remove();
	setDirtyFlag(true);
}

function setTemplateRef(elSelect) {
	var parentDiv = $(elSelect).parent('DIV').parent('DIV')[0];
	var templateRef = $(elSelect).val();
	initTree(templateRef, parentDiv);
}

function initDropTargets(index) {
	$(".droppable", $('#descriptorTemplate_' + index)).droppable({
		drop: function(event, ui) {
			var target = event.target.id;
			var source = ui.draggable[0];
			var type = source.id.split('_')[0];
			var subType = source.id.split('_')[1];
			insert(type, source, event);
			setDirtyFlag(true);
			//initDropTargets();
			return false;
		}
	});
	$(".droppable", $('#descriptorTemplate_' + index)).click(function(e) {
		saveSelection(e.target);
	}).keypress(function(e) {
		if (e.which == 13) 
        {
            e.preventDefault();
            insertNodeOverSelection($('<br/>')[0], this);
        }
		saveSelection(e.target);
	});
}

function initTree(templateRef, htmlNodeId) {
	var tree = new YAHOO.widget.TreeView(htmlNodeId);
	tree.setDynamicLoad(function(node, fnLoadComplete) {
		var nodeLabel = encodeURI(node.data.parameterId);
		var sUrl = 'templatesTreeXML.jsp?contextId=' + contextId + '&templateRef=' + templateRef + '&parent=' + nodeLabel;
		var callback = {
			success : function(oResponse) {
				var document = oResponse.responseXML;
				var xpath = new XPathExpression();
				var paramNodes = xpath.selectNodes(document, '/parameters/parameter');
				for (var i = 0; i < paramNodes.length; i++) {
					var node = paramNodes.item(i);
					var id = node.getAttribute('id');
					var name = node.getAttribute('name');
					var type = node.getAttribute('type');
					var multi = node.getAttribute('multiple');
					var nodeHTML = '<span>';
					if (type == 'value') {
						nodeHTML += '<span class="element draggable" value="' + id + '" id="element_'
								+ id + '"><b>' + name + '</b></span>';
					} else {
						nodeHTML += name;
					}
					if (multi == 'true') {
						nodeHTML += ' <span class="loop draggable" value="' + id + '" id="loop_'
								+ id + '"><b>loop</b></span>';
					}
					nodeHTML += '</span>';
					var newNode = new YAHOO.widget.HTMLNode({
						html: nodeHTML,
						parameterId: node.getAttribute('id'),
						isLeaf: (type == 'value')
					}, oResponse.argument.node, false);
					
				}
				oResponse.argument.fnLoadComplete();
				$(".draggable", $('#' + oResponse.argument.node.getElId())).draggable({
					revert : true
				});
			},

			failure : function(oResponse) {
				oResponse.argument.fnLoadComplete();
			},

			argument : {
				"node" : node,
				"fnLoadComplete" : fnLoadComplete
			},

			timeout : 2000
		};

		YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
	});
	var root = tree.getRoot();
	new YAHOO.widget.HTMLNode({
		html: "<span id='expression_draggable' class='expression draggable'><b>expression</b></span>",
		isLeaf: true
	}, root, false);
	
	new YAHOO.widget.HTMLNode({
		html: "<span id='condition_draggable' class='condition draggable'><b>condition</b></span></li>",
		isLeaf: true
	}, root, false);
	
	new YAHOO.widget.HTMLNode({
		html: '<b>' + templateRef + '</b>',
		parameterId: ''
	}, root, false);
	tree.draw();
	
	$(".draggable", $('#' + htmlNodeId)).draggable({
		revert : true
	});
}

function insert(type, sourceNode, event) {
	restoreSelection(event.target);
	var type = sourceNode.id.split('_')[0];
	var handler = SECTION_ELEMENT_HANDLERS[type];
	if (!handler) {
		alert('no handler found for type "' + type + '"');
		return;
	}
	
	var map = {
		value: ''
	};
	switch(type) {
	case 'element':
	case 'loop':
		map.value = $(sourceNode).attr('value');
	}
	handler.render(event.target, map);
}

var savedRange = [];
function saveSelection(el) {
	if (window.getSelection) {
		savedRange[el] = window.getSelection().getRangeAt(0);
	} else if (document.selection) {
		savedRange[el] = document.selection.createRange();
	}
}

function restoreSelection(el) {
	if (savedRange[el] != null) {
		if (window.getSelection) {
			var s = window.getSelection();
			if (s.rangeCount > 0)
				s.removeAllRanges();
			s.addRange(savedRange[el]);
		} else if (document.createRange) {
			window.getSelection().addRange(savedRange[el]);
		} else if (document.selection) {
			savedRange[el].select();
		}
	}
}